#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2020/5/27 10:32
# @Author : wn 
# @File: rule.py
# @SoftWare: PyCharm
# @Site:
# @Table:
# ｡◕‿◕｡｡◕‿◕｡｡◕‿◕｡


from django.shortcuts import render, HttpResponse, redirect
from Manager.models import *
from Rbac.models import *
from Manager.views.service import my_page
from django.http import JsonResponse
import json
from Django_Admin.enumType import *

from Rbac.utils.login_deco import *


@auth
def rule_list(request):
    # 当前在第几页
    off = request.GET.get('offset', None)
    # 一页几条数据
    lim = request.GET.get('limit', None)
    # 获取url后拼接的search
    search = request.GET.get('search', None)
    # 判断url后面是否拼接了search，没有，返回页面；有显示搜索条件的值
    if search is None:
        customerid = Customer.objects.all()
        return render(request, 'rule.html', {"customerid": customerid})
    else:
        # 按搜索条件获取值
        if search:
            # 如果多个主键，这filter中，连写另一个值可以吗
            r_list = Rule.objects.values().filter(ruleid__contains=search)
        else:
            r_list = Rule.objects.values()
        # 把queryset转成列表[{},{}]
        r_list = list(r_list)
        for item in r_list:
            # 联合主键，用id
            item['option'] = item['id']
            # 枚举值
            item['isclientloaded'] = IsActive_choices.get(item['isclientloaded'], None)
        result = my_page(r_list, lim, off)
        return JsonResponse(result, safe=False)


# 添加，修改，删除
def rule_modify(request):
    ##拿到登录用户id
    userid = request.session["id"]
    isdelete = Customer.objects.filter(customerid=userid).filter(
        roles__permissions__url__endswith='rule_list(delete)')
    ismodify = Customer.objects.filter(customerid=userid).filter(
        roles__permissions__url__endswith='rule_list(modify)')
    isadd = Customer.objects.filter(customerid=userid).filter(
        roles__permissions__url__endswith='rule_list(add)')
    if request.method == 'GET':
        # 联合主键，联合主键用id判断记录的唯一性
        r_id = request.GET['id']
        item = Rule.objects.values().filter(id=r_id).first()
        # print('被修改的值：', item)
        if item:
            return JsonResponse(item, safe=False)
    else:
        if request.POST.get('delete', None):
            # 删除
            if isdelete:
                rid = request.POST.get('id')
                ruleid = Rule.objects.filter(id=rid).values("ruleid").first().get("ruleid")
                crobj = Customerrulerel.objects.filter(ruleid=ruleid)
                if crobj:
                    return HttpResponse("请先删除策略用户关系！")
                try:
                    Rule.objects.filter(id=rid).delete()
                    return HttpResponse('y')
                except Exception as e:
                    # print(e)
                    return HttpResponse(e)
            else:
                return HttpResponse("该用户无操作权限！")
        else:
            data = request.POST
            try:
                if json.loads((data['id']))[0]:
                    if ismodify:
                        if Rule.objects.filter(id=json.loads(data['id'])[0]).count() >= 1:
                            # 修改,联合主键用id判断记录的唯一性
                            Rule.objects.filter(id=json.loads(data['id'])[0]).update(
                                ruleid=json.loads(data["ruleid"])[0],
                                rulepath=json.loads(data["rulepath"])[0],
                                ruleversion=json.loads(data["ruleversion"])[0],
                                rulename=json.loads(data["rulename"])[0],
                                configpath=json.loads(data["configpath"])[0],
                                customerid=json.loads(data["customerid"])[0],
                                isclientloaded=json.loads(data["isclientloaded"])[0],
                            )
                            return HttpResponse("y")
                    else:
                        return HttpResponse("该用户无操作权限！")
                else:
                    if isadd:
                        # 新增
                        ruleobj = Rule.objects.filter(ruleid=json.loads(data["ruleid"])[0])
                        if ruleobj:
                            return HttpResponse("策略ID已存在！")
                        Rule.objects.create(
                            ruleid=json.loads(data["ruleid"])[0],
                            rulepath=json.loads(data["rulepath"])[0],
                            ruleversion=json.loads(data["ruleversion"])[0],
                            rulename=json.loads(data["rulename"])[0],
                            configpath=json.loads(data["configpath"])[0],
                            customerid=json.loads(data["customerid"])[0],
                            isclientloaded=json.loads(data["isclientloaded"])[0],
                        )
                        return HttpResponse("y")
                    else:
                        return HttpResponse("该用户无操作权限！")
            except Exception as e:
                return HttpResponse(e)
        return render(request, 'rule.html')
